package no.rodland.acc.parsers;

import org.constretto.annotation.Configuration;
import org.constretto.annotation.Configure;
import org.joda.time.DateTime;
import org.joda.time.MutableDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Since: Jun 21, 2010 10:59:49 AM
 * @Author: fmr
 */
public class DateParser {
    private List<DateTimeFormatter> fmt = new ArrayList<DateTimeFormatter>();
    private static final String SEPARATOR = ",";

    @Configure
    public void configure(@Configuration(expression = "import.date_format") String dateFormat) {
        List<String> list = Arrays.asList(dateFormat.split(SEPARATOR));
        for (String s : list) {
            fmt.add(DateTimeFormat.forPattern(s));
        }
    }

    public DateTime parse(String string) {
        if (string == null || string.length() == 0) {
            return null;
        }
        string = string.replaceAll("[\"']", "");

        for (DateTimeFormatter dateTimeFormatter : fmt) {
            try {
                DateTime dt = dateTimeFormatter.parseDateTime(string);
                if (dt.getYear() < 1000) {
                    MutableDateTime mdt = new MutableDateTime(dt);
                    mdt.addYears(2000);
                    dt = new DateTime(mdt);
                }
                return dt;
            }
            catch (Exception e) {
                //Ignore
            }
        }
        return null;
    }
}
